<template>
	<view>
		<view style="background-color: #fff;
		margin: 40rpx;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		border-radius: 10px;">
			<view class="table_title" @click="getServerData1()">
				<text style="margin-right: 10rpx;">{{title}}</text>
				<uni-icons type="refreshempty" size="20"></uni-icons>
			</view>
			<view class="table_header">
				<uni-table ref="table" border emptyText="暂无更多数据">
					<uni-tr>
						<uni-th width="100" align="center" style="color: black;">实时数据</uni-th>
						<uni-th width="90" align="center" style="color: black;">进水</uni-th>
						<uni-th width="90" align="center" style="color: black;">出水</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in staticData" :key="index">
						<uni-td align="center">{{ item.name }}</uni-td>
						<uni-td align="center">{{ item.in }}</uni-td>
						<uni-td align="center">{{ item.out }}</uni-td>
					</uni-tr>
				</uni-table>
			</view>

		</view>

		<view style="display: flex;justify-content: center;">
			<view class="textTitle"><text>24小时对比</text></view>
		</view>

		<view style="background-color: #fff;
		margin: 40rpx;
		padding: 10rpx;
		display: flex;
		height: 500rpx;
		flex-direction: column;
		border-radius: 10px;">
			<view class="uni-padding-wrap uni-common-mt">
				<uni-segmented-control :current="typeCurrent" :values="items" style-type="text"
					@clickItem="onClickItem" />
			</view>
			<view class="content">
				<view style="height: 400rpx;">
					<qiun-data-charts type="line" :opts="opts" :chartData="chartData" />
				</view>
			</view>

		</view>

	</view>
</template>

<script>
	import {
		queryCycleFactorData,
		queryLastFactorData
	} from "@/api/index"
	export default {

		data() {
			return {
				items: ['进水口', '出水口'],
				staticData: [{
						name: 'CO',
						in: '174.6',
						out: '174.6'
					},
					{
						name: '氨氮',
						in: '174.6',
						out: '174.6'
					},
					{
						name: '总磷',
						in: '4.6',
						out: '4.6'
					},
					{
						name: '总氮',
						in: '4.6',
						out: '4.6'
					},
					{
						name: 'PH',
						in: '2.6',
						out: '2.6'
					}
				],
				title: '09: 23:24',
				chartData: {},
				typeCurrent: 0,
				form: {},
				opts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					height: 200,
					padding: [15, 10, 0, 15],
					enableScroll: false,
					legend: {
						fontSize: 10,
						position: "top"
					},
					dataLabel: false,
					xAxis: {
						disableGrid: true,
						rotateLabel: true,
						rotateAngle: 45,
						fontSize: 10,
						marginTop: 5
					},
					yAxis: {
						gridType: "dash",
						dashLength: 8,
						padding: 10,
						splitNumber: 3
					},
					extra: {
						line: {
							type: "curve"
						}

					},
					series: {
						labelShow: false
					}
				}
			}
		},
		onReady() {
			this.getServerData1();
			this.getServerData2("0");
		},
		methods: {
			onClickItem(e) {
				console.log('oooo1ooooo', e.currentIndex)
				this.getServerData2(e.currentIndex)
			},
			getServerData1() {
				uni.showLoading({
					title: '加载中'
				});
				this.form.cn = "2061";
				this.form.factorNames = ["化学需氧量", "总磷", "总氮", "氨氮", "pH 值"];
				this.form.flowTypes = ["0", "1"];
				queryLastFactorData(this.form).then(response => {
					console.info("ffffffff", response)
					// 使用示例
					this.staticData = this.transformData(response);
					console.info("ffffffff", this.staticData)
					const firstDataTime = response[0].datatime;
					console.info("ffffffff", firstDataTime)
					let dateString = "May 10, 2024 12:00:00 PM";
					let date = new Date(firstDataTime);

					let year = date.getFullYear();
					let month = (date.getMonth() + 1).toString().padStart(2, '0');
					let day = date.getDate().toString().padStart(2, '0');
					let hours = date.getHours().toString().padStart(2, '0');
					let minutes = date.getMinutes().toString().padStart(2, '0');
					let seconds = date.getSeconds().toString().padStart(2, '0');

					let formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
					console.log(formattedDate); // 输出格式化后的时间，精确到年月日时分秒
					this.title = formattedDate;
					setTimeout(function() {
						uni.hideLoading();
					}, 500);
				})

			},
			getServerData2(type) {
				this.form.cn = "2061";
				this.form.factorNames = ["化学需氧量", "总磷", "总氮", "氨氮", "pH 值"];

				this.form.flowTypes = [];

				if (type) {
					this.form.flowTypes.push(type);
				} else {
					this.form.flowTypes.push("0");
				}
				// 获取当前日期
				const now = new Date();
				// 格式化为 "YYYY-MM-DD" 格式
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要加 1
				const day = String(now.getDate()).padStart(2, '0');
				// 当天开始时间
				const beginTime = `${year}-${month}-${day} 00:00:00`;

				// 当天结束时间
				const endTime = `${year}-${month}-${day} 23:59:59`;

				// 设置表单字段
				this.form.beginTime = beginTime;
				this.form.endTime = endTime;
				queryCycleFactorData(this.form).then(response => {
					console.info("ddddd", response)
					// 使用示例
					const transformedData = this.transformData2(response);
					console.log("aaaaaaa", transformedData);

					const transformedCategories = transformedData.categories.map(time => time.substring(0, 5));
					transformedData.categories = transformedCategories;
					this.chartData = JSON.parse(JSON.stringify(transformedData));
				})

			},
			transformData(rawData) {
				const result = [];
				const factorMap = {};

				rawData.forEach(item => {
					const factorName = item.factorName;
					const equipmentName = item.equipmentName;
					const avgValue = item.Avg;
					if (!factorMap[factorName]) {
						factorMap[factorName] = {
							name: factorName,
							in: null,
							out: null
						};
					}

					if (equipmentName.includes("进水")) {
						factorMap[factorName].in = avgValue;
					} else {
						factorMap[factorName].out = avgValue;
					}
				});

				for (const factorName in factorMap) {
					result.push(factorMap[factorName]);
				}

				return result;
			}

			,
			transformData2(rawData) {
				const result = {
					categories: [],
					series: []
				};

				const factorMap = {};

				rawData.forEach(item => {
					console.info(item.flow_type, "-----aaaaaaaa----", this.form.flowTypes[0])
					if (item.flow_type+"" === this.form.flowTypes[0]+"") {
						console.info("aaddddddddddddd", item)
						const factorName = item.factor_name;
						const xData = item.xData;
						const yData = item.yData;
						console.info(factorName, "-----yData----", yData)
						if (!factorMap[factorName]) {
							factorMap[factorName] = {
								name: factorName,
								data: []
							};
						}

						factorMap[factorName].data = yData;
						if (result.categories.length === 0) {
							result.categories = xData.map(time => time.split(' ')[1]);
						}
					}

				});

				for (const factorName in factorMap) {
					result.series.push(factorMap[factorName]);

				}

				return result;
			}, // 下拉刷新
			onPullDownRefresh() {
				console.log('下拉刷新')
				this.getServerData1();
				this.getServerData2();
				setTimeout(() => {
					console.log('下拉刷新停止')
					uni.stopPullDownRefresh()
				}, 2000)
			},



		}
	}
</script>

<style lang="scss">
	.table_title {
		display: flex;
		width: 100%;
		flex-direction: row;
		color: #060606;
		font-size: 24rpx;
		justify-content: flex-end;
		align-items: center;
	}

	.table_header {
		width: 100%;
		margin: 20rpx 0rpx;
	}

	.textTitle {
		padding: 10rpx 40rpx;
		margin: 10rpx;
		font-size: 24rpx;
		font-weight: bold;
		background: rgb(226, 238, 254);
		border-radius: 5rpx;
	}
</style>